import React, { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { Image, StyleSheet, Text } from "react-native";
import { commonStyles } from "../../configs/commonStyle";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { IconImage } from "../../utils";
import AudioRecorderPlayer from "react-native-audio-recorder-player";
import { userStore } from "../../store";
import { windowWidth } from "../../configs/platform";
import * as Progress from "react-native-progress";

/**
 * 播放器
 * @param orderNo
 * @param onRef
 * @param recordComplete
 * @returns {JSX.Element}
 * @constructor
 */
const Player = ({ onRef, showPlayer },ref) => {
  const [playTime, setPlayTime] = useState("00:00:00");
  const [duration, setDuration] = useState("00:00:00");
  const [isPlaying, setIsPlaying] = useState(true);
  const [currentPositionSec, setCurrentPositionSec] = useState(0);
  const [currentDurationSec, setCurrentDurationSec] = useState(1);

  const audioRecorderPlayer = new AudioRecorderPlayer();

  useEffect(() => {
    logger("触发播放", showPlayer);
    if (!IsNullOrEmpty(showPlayer)) {
      onStartPlay(showPlayer);
    }
  }, [showPlayer]);

  useImperativeHandle(onRef, () => ({
    play: (recordPath) => {
      // onStartPlay(recordPath);
    },
    stop: async () => {
      await onStopPlay();
    },
  }));

  const onStartPlay = async (recordPath) => {
    logger("onStartPlay", recordPath);
    // const msg = await audioRecorderPlayer.startPlayer('http://qw8ou93e4.hn-bkt.clouddn.com/202108030008_1628405425504%E7%9A%84%E5%89%AF%E6%9C%AC.m4a');
    const msg = await audioRecorderPlayer.startPlayer(recordPath);
    setIsPlaying(true);
    logger("开始播放", msg);
    audioRecorderPlayer.addPlayBackListener((e) => {
      logger("播放进度", e.currentPosition, e.duration);
      if (!IsNullOrEmpty(e.duration) && !IsNullOrEmpty(e.currentPosition) && e.duration != NaN && e.currentPosition != NaN) {
        setPlayTime(audioRecorderPlayer.mmssss(
          Math.floor(e.currentPosition),
        ));
        setDuration(audioRecorderPlayer.mmssss(Math.floor(e.duration)));
        setCurrentPositionSec(e.currentPosition);
        setCurrentDurationSec(e.duration);

        if (e.currentPosition == e.duration) {
          logger("播放完成");
          onStopPlay();
        }
      }
    });
  };

  const onPausePlay = React.useCallback(async () => {
    logger("暂停播放");
    await audioRecorderPlayer.pausePlayer();
    setIsPlaying(false);
  }, []);

  const onResumePlay = React.useCallback(async () => {
    logger("继续播放");
    await audioRecorderPlayer.resumePlayer();
    setIsPlaying(true);
  }, []);


  const onStopPlay = React.useCallback(async () => {
    logger("停止播放");
    await audioRecorderPlayer.stopPlayer();
    audioRecorderPlayer.removePlayBackListener();
    userStore.setValue("playingNo", "");
    userStore.setValue("showPlayer", "");
  }, []);

  return (
    <View useSafeArea style={styles.container}>
      <View style={styles.recorderWrap}>
        <View marginT-5>
          <Progress.Bar
            color={"#ffffff80"}
            width={windowWidth - 60}
            height={5}
            progress={currentPositionSec / currentDurationSec}
            borderRadius={9}
          />
          <View row centerV spread marginT-5>
            <Text style={commonStyles.text_gray_10}>{playTime}</Text>
            <Text style={commonStyles.text_gray_10}>{duration}</Text>
          </View>
          <View row center marginT-10>
            {
              isPlaying ? <TouchableOpacity centerH activeOpacity={1} onPress={onPausePlay}>
                  <Image source={IconImage.btn_pause} style={{ width: 43, height: 43 }} />
                </TouchableOpacity>
                :
                <TouchableOpacity centerH activeOpacity={1} onPress={onResumePlay}>
                  <Image source={IconImage.btn_play} style={{ width: 43, height: 43 }} />
                </TouchableOpacity>
            }
            <TouchableOpacity centerH activeOpacity={1} onPress={onStopPlay}>
              <Image source={IconImage.btn_stop} style={{ width: 43, height: 43, marginLeft: 20 }} />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  );
};

export default forwardRef(Player);

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFill,
    backgroundColor: "#00000080",
    justifyContent: "flex-end",
  },
  recorderWrap: {
    backgroundColor: "black",
    paddingVertical: 20,
    paddingHorizontal: 15,
    justifyContent: "center",
    alignItems: "center",
  },
  button: {
    flexDirection: "row",
    alignItems: "center",
    marginTop: 20,
  },
});
